<template>
  <view class="message-page">
    <!-- 自定义Tab标签页 -->
    <view class="custom-tabs">
      <view 
        class="tab-item"
        :class="{ 'tab-active': currentTab === 0 }"
        @click="handleTabChange(0)"
      >
        <text class="tab-text">聊天</text>
        <view class="tab-badge" v-if="conversationUnreadCount > 0">
          {{ conversationUnreadCount > 99 ? '99+' : conversationUnreadCount }}
        </view>
      </view>
      <view 
        class="tab-item"
        :class="{ 'tab-active': currentTab === 1 }"
        @click="handleTabChange(1)"
      >
        <text class="tab-text">通知</text>
        <view class="tab-badge" v-if="notificationUnreadCount > 0">
          {{ notificationUnreadCount > 99 ? '99+' : notificationUnreadCount }}
        </view>
      </view>
      <view class="tab-line" :style="{ left: currentTab === 0 ? '25%' : '75%' }"></view>
    </view>

    <!-- 聊天会话列表 -->
    <view class="conversation-list" v-show="currentTab === 0">
      <view 
        v-for="conversation in conversationList" 
        :key="conversation.id"
        class="conversation-item"
        @click="openChat(conversation)"
      >
        <view class="avatar-section">
          <u-avatar 
            :src="getConversationAvatar(conversation)" 
            size="50"
          ></u-avatar>
          <u-badge 
            v-if="conversation.unreadCount > 0"
            :value="conversation.unreadCount > 99 ? '99+' : conversation.unreadCount"
            :offset="[-5, 5]"
          ></u-badge>
        </view>
        
        <view class="content-section">
          <view class="header">
            <text class="name">{{ getConversationName(conversation) }}</text>
            <text class="time">{{ formatTime(conversation.lastMessageTime) }}</text>
          </view>
          <view class="message">
            <text class="content">{{ conversation.lastMessageContent || '暂无消息' }}</text>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <u-empty 
        v-if="!loading && conversationList.length === 0"
        text="暂无会话"
        mode="list"
      ></u-empty>
    </view>

    <!-- 系统通知列表 -->
    <view class="notification-list" v-show="currentTab === 1">
      <view 
        v-for="notification in notificationList" 
        :key="notification.id"
        class="notification-item"
        @click="handleNotificationClick(notification)"
      >
        <view class="notification-icon">
          <u-icon 
            :name="getNotificationIcon(notification.type)" 
            size="40" 
            :color="getNotificationColor(notification.type)"
          ></u-icon>
        </view>
        
        <view class="notification-content">
          <view class="notification-header">
            <text class="notification-title">{{ notification.title }}</text>
            <view class="notification-badge" v-if="notification.priority === 'HIGH' || notification.priority === 'URGENT'">
              <text class="badge-text">{{ notification.priority === 'URGENT' ? '紧急' : '重要' }}</text>
            </view>
          </view>
          <text class="notification-text">{{ notification.content }}</text>
          <view class="notification-footer">
            <view class="notification-type">
              <u-tag 
                :text="getTypeText(notification.type)" 
                size="mini"
                :type="getTypeTagType(notification.type)"
              ></u-tag>
            </view>
            <text class="notification-time">{{ formatTime(notification.sentAt || notification.createdAt) }}</text>
          </view>
        </view>
        
        <view class="notification-status" v-if="notification.status === 'UNREAD'">
          <view class="unread-dot"></view>
        </view>
      </view>

      <!-- 空状态 -->
      <u-empty 
        v-if="!loading && notificationList.length === 0"
        text="暂无系统通知"
        mode="list"
      ></u-empty>
    </view>

    <!-- 加载中 -->
    <u-loading-page :loading="loading"></u-loading-page>
  </view>
</template>

<script>
import { getConversationList, createPrivateConversation, getSystemMessages } from '@/api/message'
import { formatTime } from '@/utils/date'

export default {
  name: 'MessageIndex',
  data() {
    return {
      loading: false,
      currentTab: 0,
      conversationList: [],
      notificationList: [],
      conversationUnreadCount: 0,
      notificationUnreadCount: 0,
      showAddMenu: false,
      showNewChatModal: false,
      newChatForm: {
        targetUserId: ''
      }
    }
  },
  
  onLoad() {
    this.loadData()
  },
  
  onShow() {
    // 页面显示时刷新数据
    this.loadData()
  },
  
  onPullDownRefresh() {
    this.loadData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    // 加载数据
    async loadData() {
      if (this.currentTab === 0) {
        await this.loadConversations()
      } else {
        await this.loadNotifications()
      }
    },
    
    // Tab切换
    handleTabChange(index) {
      this.currentTab = index
      this.loadData()
    },
    
    // 加载会话列表
    async loadConversations() {
      try {
        this.loading = true
        const res = await getConversationList()
        if (res.code === 200) {
          this.conversationList = res.data || []
          // 计算未读数量
          this.conversationUnreadCount = this.conversationList.reduce((sum, item) => {
            return sum + (item.unreadCount || 0)
          }, 0)
        }
      } catch (error) {
        console.error('加载会话列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载系统通知
    async loadNotifications() {
      try {
        this.loading = true
        const res = await getSystemMessages(50)
        if (res.code === 200) {
          this.notificationList = res.data || []
          // 计算未读数量
          this.notificationUnreadCount = this.notificationList.filter(item => {
            return item.status === 'UNREAD'
          }).length
        }
      } catch (error) {
        console.error('加载系统通知失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'error'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 搜索会话
    handleSearch() {
      // TODO: 实现搜索功能
      console.log('搜索:', this.searchKeyword)
    },
    
    // 打开聊天页面
    openChat(conversation) {
      uni.navigateTo({
        url: `/pages/message/chat?conversationId=${conversation.id}&name=${encodeURIComponent(this.getConversationName(conversation))}`
      })
    },
    
    // 获取会话名称
    getConversationName(conversation) {
      if (conversation.type === 'GROUP') {
        return conversation.name || '群聊'
      } else {
        // 私聊显示对方用户名
        return this.getOtherUserName(conversation) || '私聊'
      }
    },
    
    // 获取会话头像
    getConversationAvatar(conversation) {
      if (conversation.type === 'GROUP') {
        return conversation.avatar || '/static/icons/group-avatar.png'
      } else {
        // 私聊显示对方用户头像
        return this.getOtherUserAvatar(conversation) || '/static/icons/default-avatar.png'
      }
    },
    
    // 获取对方用户名
    getOtherUserName(conversation) {
      try {
        const userInfo = uni.getStorageSync('userInfo')
        const currentUserId = userInfo.id
        const participants = JSON.parse(conversation.participants || '[]')
        
        // 找到对方用户ID
        const otherUserId = participants.find(id => id !== currentUserId)
        
        // TODO: 这里应该从用户信息中获取真实姓名
        // 暂时返回用户ID
        return conversation.otherUserName
      } catch (error) {
        console.error('解析参与者信息失败:', error)
        return '私聊'
      }
    },
    
    // 获取对方用户头像
    getOtherUserAvatar(conversation) {
      // TODO: 这里应该从用户信息中获取真实头像
      return conversation.otherUserAvatar
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return formatTime(time)
    },
    
    // 处理添加操作
    handleAddAction(action) {
      if (action.value === 'private') {
        this.showNewChatModal = true
      } else if (action.value === 'group') {
        uni.navigateTo({
          url: '/pages/message/create-group'
        })
      }
    },
    
    // 处理通知点击
    handleNotificationClick(notification) {
      // 如果有链接地址，跳转到指定页面
      if (notification.linkUrl) {
        uni.navigateTo({
          url: notification.linkUrl
        })
      } else {
        // 显示通知详情
        uni.showModal({
          title: notification.title,
          content: notification.content,
          showCancel: false,
          confirmText: '我知道了'
        })
      }
      
      // 标记为已读
      if (notification.status === 'UNREAD') {
        this.markNotificationAsRead(notification.id)
      }
    },
    
    // 标记通知为已读
    async markNotificationAsRead(messageId) {
      try {
        const { markMessageAsRead } = require('@/api/message')
        await markMessageAsRead(messageId)
        // 更新本地状态
        const index = this.notificationList.findIndex(n => n.id === messageId)
        if (index !== -1) {
          this.notificationList[index].status = 'READ'
        }
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    },
    
    // 获取通知图标
    getNotificationIcon(type) {
      const icons = {
        SYSTEM: 'setting-fill',
        ACTIVITY: 'gift-fill',
        ANNOUNCEMENT: 'volume-fill'
      }
      return icons[type] || 'bell-fill'
    },
    
    // 获取通知颜色
    getNotificationColor(type) {
      const colors = {
        SYSTEM: '#1890ff',
        ACTIVITY: '#52c41a',
        ANNOUNCEMENT: '#fa8c16'
      }
      return colors[type] || '#5daf34'
    },
    
    // 获取类型文本
    getTypeText(type) {
      const texts = {
        SYSTEM: '系统',
        ACTIVITY: '活动',
        ANNOUNCEMENT: '公告'
      }
      return texts[type] || '通知'
    },
    
    // 获取类型标签类型
    getTypeTagType(type) {
      const types = {
        SYSTEM: 'info',
        ACTIVITY: 'success',
        ANNOUNCEMENT: 'warning'
      }
      return types[type] || 'primary'
    },
    
    // 创建新聊天
    async createNewChat() {
      if (!this.newChatForm.targetUserId) {
        uni.showToast({
          title: '请输入用户ID',
          icon: 'error'
        })
        return
      }
      
      try {
        const res = await createPrivateConversation(this.newChatForm.targetUserId)
        if (res.code === 200) {
          uni.showToast({
            title: '创建成功',
            icon: 'success'
          })
          this.showNewChatModal = false
          this.newChatForm.targetUserId = ''
          this.loadConversations()
        }
      } catch (error) {
        console.error('创建会话失败:', error)
        uni.showToast({
          title: '创建失败',
          icon: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.message-page {
  height: 100vh;
  background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
  display: flex;
  flex-direction: column;
}

.custom-tabs {
  display: flex;
  background: white;
  padding: 0 60rpx;
  position: relative;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 30rpx 0;
    position: relative;
    transition: all 0.3s ease;
    
    .tab-text {
      font-size: 32rpx;
      color: #666;
      font-weight: 500;
      transition: all 0.3s ease;
    }
    
    .tab-badge {
      position: absolute;
      top: 20rpx;
      right: 50%;
      margin-right: -60rpx;
      background: #ff6b6b;
      color: white;
      font-size: 20rpx;
      padding: 4rpx 10rpx;
      border-radius: 20rpx;
      min-width: 32rpx;
      text-align: center;
      font-weight: bold;
    }
    
    &.tab-active {
      .tab-text {
        color: #5daf34;
        font-weight: 700;
      }
    }
  }
  
  .tab-line {
    position: absolute;
    bottom: 0;
    width: 60rpx;
    height: 6rpx;
    background: linear-gradient(90deg, #5daf34, #7cb342);
    border-radius: 3rpx;
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    transform: translateX(-50%);
  }
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  background: white;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  background: white;
  border-bottom: 2rpx solid #f0f0f0;
  transition: all 0.3s ease;
  
  &:active {
    background-color: #f8f9fa;
  }
  
  .avatar-section {
    position: relative;
    margin-right: 24rpx;
  }
  
  .content-section {
    flex: 1;
    min-width: 0;
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;
      
      .name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
      
      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .message {
      .content {
        font-size: 28rpx;
        color: #666;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 0;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 28rpx 30rpx;
  background: white;
  margin: 0 20rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  position: relative;
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(-4rpx);
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  }
  
  .notification-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: linear-gradient(135deg, #f0f9ff, #e6f4ff);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 24rpx;
    flex-shrink: 0;
  }
  
  .notification-content {
    flex: 1;
    min-width: 0;
    
    .notification-header {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;
      gap: 12rpx;
      
      .notification-title {
        font-size: 32rpx;
        font-weight: 700;
        color: #333;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .notification-badge {
        background: linear-gradient(135deg, #ff6b6b, #ff8a80);
        padding: 6rpx 14rpx;
        border-radius: 16rpx;
        flex-shrink: 0;
        
        .badge-text {
          font-size: 20rpx;
          color: white;
          font-weight: bold;
        }
      }
    }
    
    .notification-text {
      display: block;
      font-size: 28rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 16rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    .notification-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .notification-type {
        flex-shrink: 0;
      }
      
      .notification-time {
        font-size: 24rpx;
        color: #999;
        margin-left: 12rpx;
      }
    }
  }
  
  .notification-status {
    position: absolute;
    top: 28rpx;
    right: 30rpx;
    
    .unread-dot {
      width: 16rpx;
      height: 16rpx;
      background: #ff6b6b;
      border-radius: 50%;
      animation: pulse-dot 2s infinite;
    }
  }
}

@keyframes pulse-dot {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.2);
  }
}

.new-chat-form {
  padding: 40rpx 20rpx;
}
</style>
